﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Configuration;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Net;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;

using NUnit.Framework;


namespace AUCS
{
    public partial class MainForm : Form
    {
        XmlDocument filehierarchy;
        TcpClient client;
        Stream TCPStream;
        StreamReader TCPsr;
        StreamWriter TCPsw;
        FileManager mFileManager;

        string serverHostname = "";
        int serverPort = 2055;

        string username = "";
        string password = "";

        public MainForm()
        {
            InitializeComponent();

            filehierarchy = new XmlDocument();
            mFileManager = new FileManager(filehierarchy, serverTreeView);
            toolTip.SetToolTip(UsernameTextBox, "Please enter your Username");
            toolTip.SetToolTip(PasswordTextBox, "Please enter your Password");
        }

        private void Login()
        {
            if (!validateLoginInfo()) return;
            while (serverHostname == "") getServerInfo();

            try
            {
                client = new TcpClient(serverHostname, serverPort);
            }
            catch(Exception e)
            {
                MessageBox.Show("Error while connecting to server;" + System.Environment.NewLine + e.Message,
                    "AUCS application error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {                
                TCPStream = client.GetStream();
                TCPsr = new StreamReader(TCPStream);
                TCPsw = new StreamWriter(TCPStream);
                TCPsw.AutoFlush = true;

                TCPsw.WriteLine(username + ":" + password);
                if (TCPsr.ReadLine() == "Granted")
                {
                    filehierarchy.InnerXml = TCPsr.ReadToEnd();

                    mFileManager.populateTreeView(serverHostname, serverPort);
                }
                else
                {
                    MessageBox.Show("Username or Password incorrect", "AUCS application error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                TCPStream.Close();
            }
            catch
            {
                
            }
            finally
            {
                client.Close();
            }
        }

        //Cleans user input and throws an error if nothing was entered
        private bool validateLoginInfo()
        {
            username = CleanInput(UsernameTextBox.Text);
            password = CleanInput(PasswordTextBox.Text);

            // If Username or password is empty after cleaning; Turn their textBoxes pink.
            bool proceed = true;
            if (username == "")
            {
                UsernameTextBox.BackColor = Color.Pink;
                proceed = false;
            }
            else UsernameTextBox.BackColor = Color.White;

            if (password == "")
            {
                PasswordTextBox.BackColor = Color.Pink;
                proceed = false;
            }
            else PasswordTextBox.BackColor = Color.White;

            return proceed;
        }

        //Shows the server info form and retrieves it's public hostname and portnumber fields
        private void getServerInfo()
        {
            ServerInfo ServerInfoDialog = new ServerInfo(serverHostname, serverPort);
            ServerInfoDialog.ShowDialog();
            serverHostname = ServerInfoDialog.hostName;
            serverPort = ServerInfoDialog.port;

            ConfigurationManager.AppSettings["hostname"] = serverHostname;
            ConfigurationManager.AppSettings["port"] = serverPort.ToString();
        }

        //If the user presses the enter key while the username or password fields are in focus, push through to login
        void TextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                e.Handled = true;
                Login();
            }
        }

        String CleanInput(string strIn)
        {
            // Replace invalid characters with empty strings.
            return Regex.Replace(strIn, @"[^\w\.@-]", "");
        }

        private void LoginBtn_Click(object sender, EventArgs e) { Login(); }
        private void serverInformationToolStripMenuItem_Click(object sender, EventArgs e) { getServerInfo(); }

        // Debug message text box appears at bottom of main form, use these methods to write to it and clear.
        // debugWrite prepends text to debugTextBox's contents
        private void debugWrite(string text) { debugTextBox.Text = text + debugTextBox.Text; }
        private void debugWriteLine(string text) { debugWrite(text + System.Environment.NewLine); }
        private void ExitApp() { this.Close(); }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e) { ExitApp(); }
    }
}
